package wsepForum.ui.swing.innerPanels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;

import wsepForum.domain.exceptions.UnAuthorizedException;
import wsepForum.network.common.GUIAnswer;
import wsepForum.network.common.GUIAnswer.AnswerType;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.persistance.exceptions.WrongUserNameException;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.workers.ForumWorker;

public class EditUserDetailsPanel extends AInnerPanel {
	
	/**
	 *
	 */
	private static final long serialVersionUID = -3335831414793056653L;

	/**
	 * Create the panel.
	 */
	public EditUserDetailsPanel(AOuterPanel oPanel, final Vector<String> usernameList) {
		super(oPanel);
		setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
		setLayout(null);
		setBackground(new Color(230, 230, 250));
		setBounds(20, 93, 716, 364);

		JLabel lblLogin = new JLabel("Edit Details");
		lblLogin.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		lblLogin.setHorizontalAlignment(SwingConstants.CENTER);
		lblLogin.setBounds(269, 11, 177, 40);
		add(lblLogin);

		JLabel lblChangePassword = new JLabel("Change Password");
		lblChangePassword.setHorizontalAlignment(SwingConstants.CENTER);
		lblChangePassword.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		lblChangePassword.setBounds(269, 167, 177, 40);
		add(lblChangePassword);


		JLabel lblOldPassword = new JLabel("Old Password");
		lblOldPassword.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblOldPassword.setHorizontalAlignment(SwingConstants.RIGHT);
		lblOldPassword.setBounds(181, 211, 98, 26);
		add(lblOldPassword);


		JLabel lblNewPassword = new JLabel("New Password");
		lblNewPassword.setHorizontalAlignment(SwingConstants.RIGHT);
		lblNewPassword.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblNewPassword.setBounds(181, 248, 98, 26);
		add(lblNewPassword);


		final JTextField oldPasswordField = new JPasswordField();
		oldPasswordField.setBounds(293, 215, 153, 20);
		add(oldPasswordField);
		oldPasswordField.setColumns(10);


		final JTextField newPasswordField = new JPasswordField();
		newPasswordField.setColumns(10);
		newPasswordField.setBounds(293, 252, 153, 20);
		add(newPasswordField);
		
		final JPasswordField newPasswordAgainField = new JPasswordField();
		newPasswordAgainField.setColumns(10);
		newPasswordAgainField.setBounds(293, 287, 153, 20);
		add(newPasswordAgainField);
		
		final JLabel lblNewPasswordAgain = new JLabel("New Password Again");
		lblNewPasswordAgain.setHorizontalAlignment(SwingConstants.RIGHT);
		lblNewPasswordAgain.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblNewPasswordAgain.setBounds(153, 283, 126, 26);
		add(lblNewPasswordAgain);

		JButton btnChange = new JButton("Update");
		btnChange.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnChange.setBounds(366, 317, 80, 23);
		btnChange.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						String oldPassword = oldPasswordField.getText();
						String newPassword = newPasswordField.getText();
						String newPasswordAgain = new String(newPasswordAgainField.getPassword());
						AInnerPanel returnedPanel = EditUserDetailsPanel.this;
						if( !oldPassword.isEmpty() && !newPassword.isEmpty() ){
							if (newPasswordAgain.equals(newPassword)) {
								GUIAnswer changeAns = request(RequestType.CHNG_PASS, new Object[] {oldPassword,newPassword});
								outerPanel.setNumOfConnected(changeAns.getNumOfConnected());
								if((changeAns.getAnswerType().equals(AnswerType.ANSWER)) && ((Boolean)changeAns.getArguments()[0])){
									GUIAnswer userListAns = request(RequestType.GET_MNG_USER_LIST, new Object[]{});
									outerPanel.setNumOfConnected(userListAns.getNumOfConnected());
									if((userListAns.getAnswerType().equals(AnswerType.ANSWER))&&(userListAns.getArguments().length==1)){
										returnedPanel = new EditUserDetailsPanel(outerPanel,(Vector<String>) userListAns.getArguments()[0]);
										JOptionPane.showMessageDialog(null, "Password changed successfuly");										
									}
									else{
										returnedPanel = handleCngPassExceptions((Exception) changeAns.getArguments()[0]);
									}
								}
								else returnedPanel = handleCngPassExceptions((Exception) changeAns.getArguments()[0]);
							}
							else {
								JOptionPane.showMessageDialog(null, "New password fields do not match. Please type again.");
							}
						}
						else {
							JOptionPane.showMessageDialog(null, "Please make sure all fields have been filled");
						}
						return returnedPanel;
					}
					
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleCngPassExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleCngPassExceptions(e));
						}
					}
					
					private AInnerPanel handleCngPassExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (WrongUserNameException e) {
							JOptionPane.showMessageDialog(null, "the user " + e.getWrongUsername() + " was deleted from the system,\nand therefore cannot be edited ", "Section deleted",JOptionPane.ERROR_MESSAGE);
							return EditUserDetailsPanel.this;
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "you are not authorized to do that", "Unauthorized use",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! can't change password\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return EditUserDetailsPanel.this;
						}
					}	
				};
				worker.execute();
			}
		});
		add(btnChange);
		
		
		
		final JComboBox listOfUsers = new JComboBox(usernameList);
		listOfUsers.setBounds(293, 74, 153, 20);
		add(listOfUsers);
		
		JLabel lblUser = new JLabel("User");
		lblUser.setHorizontalAlignment(SwingConstants.RIGHT);
		lblUser.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblUser.setBounds(181, 70, 98, 26);
		add(lblUser);

		JButton btnRemoveUser = new JButton("Remove User\r\n");
		btnRemoveUser.setFont(new Font("Tahoma", Font.PLAIN, 9));
		btnRemoveUser.setBounds(469, 73, 91, 23);
		btnRemoveUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
							GUIAnswer ans = request(RequestType.REMOVE_USER, new Object[] {usernameList.get(listOfUsers.getSelectedIndex())});
							outerPanel.setNumOfConnected(ans.getNumOfConnected());
							AInnerPanel returnedPanel = null;
							if(ans.getAnswerType().equals(AnswerType.ANSWER)){
								GUIAnswer userListAns = request(RequestType.GET_MNG_USER_LIST, new Object[]{});
								outerPanel.setNumOfConnected(ans.getNumOfConnected());
								if((userListAns.getAnswerType().equals(AnswerType.ANSWER))&&(userListAns.getArguments().length==1)){
									returnedPanel = new EditUserDetailsPanel(outerPanel,(Vector<String>) userListAns.getArguments()[0]);
									JOptionPane.showMessageDialog(null, "User " + usernameList.get(listOfUsers.getSelectedIndex()) + " removed successfuly");										
								}
								else{
									returnedPanel = handleSubmitExceptions((Exception)ans.getArguments()[0]);
								}
							}
							else {
								returnedPanel = handleSubmitExceptions((Exception)ans.getArguments()[0]);
							}
						return returnedPanel;
					}
					
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleSubmitExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleSubmitExceptions(e));
						}
					}
					
					private AInnerPanel handleSubmitExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (WrongUserNameException e) {
							JOptionPane.showMessageDialog(null, "the user " + e.getWrongUsername() + " was deleted from the system,\nand therefore cannot be edited", "User deleted",JOptionPane.ERROR_MESSAGE);
							return EditUserDetailsPanel.this;
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "You are not authorized to remove " + usernameList.get(listOfUsers.getSelectedIndex()),"Unauthorized use",JOptionPane.ERROR_MESSAGE);
							return EditUserDetailsPanel.this;
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return EditUserDetailsPanel.this;
						}
					}
				};
				worker.execute();
			}
		});
		add(btnRemoveUser);
		
		
	}
}


